package org.yyjkcache.thread;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 线程池服务
 * 
 * @author zhangwei
 *
 */
public class CollectThreadPool {
	private static Logger logger = LogManager.getLogger(CollectThreadPool.class);
	private ExecutorService service;
	private Runnable thread;
	private int threadnumber = 0;
	private Callable<String> callable;

	/**
	 * 运行线程(如果number等于-1,将启动线程池中的所有线程)
	 * 
	 * @param number
	 *            线程数
	 * @param block
	 *            是否阻塞主线程
	 */
	public void fullRun(int number, boolean block) {
		if (number == -1) {
			number = threadnumber;
		}
		for (int index = 0; index < number; index++) {
			service.submit(callable);
		}
		service.shutdown(); // 发送shutdown命令锁定线程池 排斥新添加任务直到任务结束
		try {
			if (block) {
				logger.info("主线程已经进入阻塞状态!");
				while (!service.isTerminated()) {
					Thread.sleep(50);
				}
				logger.info("任务执行完毕:" + service.isTerminated());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化线程池
	 * 
	 * @param mythread  自定义的线程
	 */
	public void initThreadPool(Runnable mythread) {
		threadnumber=Runtime.getRuntime().availableProcessors()+1;
		logger.info("初始化线程数:"+threadnumber);
		this.service = Executors.newFixedThreadPool(threadnumber);// 创建线程池，线程数与CPU核心数一致
		this.thread = mythread;
		this.callable = Executors.callable(thread, "成功");
		logger.info("线程池初始化完成");
	}

	/**
	 * 立即关闭线程池
	 */
	public void closeThreadPool() {
		service.shutdownNow(); // 关闭线程池
	}
}
